import vueRouter from 'vue-router'
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

// 创建并暴露一个路由器
const router = new vueRouter({
  routes:[
    {
      name: 'about',
      path:'/about',
      component: About,
      meta:{title:'关于'}
    },
    {
      name: 'home',
      path:'/home',
      component: Home,
      meta:{title:'主页'},
      children:[
        {
          name:'news',
          path:'news',
          meta:{isAuth:true},
          component:News,
          meta:{title:'新闻'}
        },
        {
          name: 'message',
          path:'message',
          component:Message,
          meta:{isAuth:true, title:'消息'},
          children:[
            {
              name:'detail',
              path:'detail/:id/:title',
              component:Detail,  
              props($route){
                return {
                  id: $route.params.id,
                  title: $route.params.title
                }
              }

            }
          ]
        }
      ]
    }
  ]
})

// 全局前置路由守卫 —— 初始化、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  if(to.meta.isAuth) {
    if(localStorage.getItem('user') === 'lingchen'){
      next()
    }else{
      alert('用户' + localStorage.getItem('name') + '无权限')
    }
  }else{
    next()
  }
})

// 后置路由守卫 —— 初始化、每次路由切换完成之后被调用
router.afterEach((to, from) => {
  document.title = to.meta.title || '凌宸'
})

export default router